package com.neusoft.controller;

import com.neusoft.common.Result;
import com.neusoft.service.IFileService;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletResponse;
import java.io.*;
import java.net.URLEncoder;

@RestController
@RequestMapping("/file")
public class FileController {

    @Resource
    private IFileService fileService;

    /**
     * 上传文件
     * @param file
     * @return
     * @throws Exception
     */
    @PostMapping
    public Result<?> uploadFile (MultipartFile file) throws Exception {
        return Result.success(fileService.uploadFile(file));
    }

    @GetMapping
    public void downLoadFile(HttpServletResponse response) throws IOException {
        try {
            // 根据文件路径创建文件对象
            File file = new File("D:\\ZhiBoBanLv\\picture\\woman1.jpeg");
            // 获取文件的名称
            String fileName = file.getName();
            // 得到小写的名字
            String s = fileName.substring(fileName.lastIndexOf(".") + 1).toLowerCase();
            // 根据文件创建字节输入流
            FileInputStream fileInputStream = new FileInputStream(file);
            // 存取的输入流
            BufferedInputStream bufferedInputStream = new BufferedInputStream(fileInputStream);
            // 缓存的容器
            byte[] bytes = new byte[bufferedInputStream.available()];
            //
            fileInputStream.read(bytes);
            // 关闭文件输入流
            fileInputStream.close();
            // 清空response
            response.reset();
            // 设置请求头
            response.setCharacterEncoding("UTF-8");
            //Content-Disposition的作用：告知浏览器以何种方式显示响应返回的文件，用浏览器打开还是以附件的形式下载到本地保存
            //attachment表示以附件方式下载 inline表示在线打开 "Content-Disposition: inline; filename=文件名.mp3"
            // filename表示文件的默认名称，因为网络传输只支持URL编码的相关支付，因此需要将文件名URL编码后进行传输,前端收到后需要反编码才能获取到真正的名称
            response.addHeader("Content-Disposition", "attachment;filename=" + URLEncoder.encode(fileName, "UTF-8"));
            // 告知浏览器文件的大小
            response.addHeader("Content-Length", "" + file.length());
            OutputStream outputStream = new BufferedOutputStream(response.getOutputStream());
            response.setContentType("application/octet-stream");
            outputStream.write(bytes);
            outputStream.flush();
        } catch (IOException ex) {
            ex.printStackTrace();
        }
    }
}

